package org.xbdframework.context.support;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import org.xbdframework.context.XbdApplicationEvent;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.context.ApplicationListener;

public abstract class AbstractXbdApplicationEventListenerAdapter<T extends XbdApplicationEvent>
		implements ApplicationListener<T> {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	protected abstract void execute(T t);

	@Override
	public void onApplicationEvent(T t) {
		if (this.logger.isDebugEnabled()) {
			this.logger.debug("事件监听器{}监听到来源{}的事件，于{}处理开始，事件详细内容为{}",
					new Object[] { this.getClass().getSimpleName(), t.getSource(),
							LocalDateTime.now().format(
									DateTimeFormatter.ofPattern("yyyy/mm/dd HH:MM:SS")),
							t.toString() });
		}

		try {
			execute(t);
		}
		catch (Throwable ex) {
			XbdApplicationEventListenerUnexpectedException xbdApplicationEventListenerUnexpectedException = new XbdApplicationEventListenerUnexpectedException(
					ex.getMessage(), ex);

			xbdApplicationEventListenerUnexpectedException.setEvent(t);

			throw xbdApplicationEventListenerUnexpectedException;
		}

		if (this.logger.isDebugEnabled()) {
			this.logger.debug("事件监听器{}监听到来源{}的事件，于{}处理完成，事件详细内容为{}",
					new Object[] { this.getClass().getSimpleName(), t.getSource(),
							LocalDateTime.now().format(
									DateTimeFormatter.ofPattern("yyyy/mm/dd HH:MM:SS")),
							t.toString() });
		}
	}

}
